﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>LINQ queries | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="LINQ queries | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.0.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="linq-queries">LINQ queries</h1>

<p>see the mongodb c# driver <a href="http://mongodb.github.io/mongo-csharp-driver/2.11/reference/driver/crud/linq/">linq documentation</a> to see which LINQ operations are available.
also see the c# driver <a href="http://mongodb.github.io/mongo-csharp-driver/2.11/reference/driver/expressions/">expressions documentation</a> to see all supported expressions.</p>
<div class="TIP">
<h5>Tip</h5>
<p>don't forget to first import the mongodb linq extensions with <strong>using MongoDB.Driver.Linq;</strong></p>
</div>
<h2 id="query-collections">Query collections</h2>
<pre><code class="lang-csharp">var author = await (from a in DB.Queryable&lt;Author&gt;()
                    where a.Name.Contains(&quot;Eckhart&quot;)
                    select a).FirstOrDefaultAsync();
</code></pre>
<h2 id="forward-relationship-access">Forward relationship access</h2>
<p>every <code>Many&lt;T&gt;</code> property gives you access to an <code>IQueryable</code> of child entities.</p>
<pre><code class="lang-csharp">var authors = from a in book.Authors.ChildrenQueryable()
              select a;
</code></pre>
<p>this <code>.ChildrenQueryable()</code> is an already filtered <code>IQueryable</code> of child entities. For ex: the above <code>.ChildrenQueryable()</code> is limited to only the Authors of that particular <code>Book</code> entity. It does not give you access to all of the <code>Author</code> entities in the Authors collection.</p>
<h2 id="reverse-relationship-access">Reverse relationship access</h2>
<p>for example, if you'd like to get all the books belonging to a genre, you can do it with the help of <code>.ParentsQueryable()</code> like so:</p>
<pre><code class="lang-csharp">var books = book.Genres
                .ParentsQueryable&lt;Book&gt;(&quot;GenreID&quot;);
</code></pre>
<p>you can also pass in an <code>IQueryable</code> of genres and get an <code>IQueryable</code> of books like shown below:</p>
<pre><code class="lang-csharp">var query = genre.Queryable()
                 .Where(g =&gt; g.Name.Contains(&quot;Music&quot;));

var books = book.Genres
                .ParentsQueryable&lt;Book&gt;(query);
</code></pre>
<p>it is basically a convenience method instead of having to do a manual join like the one shown below in order to access parents of one-to-many or many-to-many relationships.</p>
<h2 id="relationship-joins">Relationship joins</h2>
<p><code>Many&lt;T&gt;.JoinQueryable()</code> gives you access to all the join records of that particular entity relationship. A join record has two properties <code>ParentID</code> and <code>ChildID</code> that you can use to gain access to parent Entities like so:</p>
<pre><code class="lang-csharp">//LINQ syntax
var allBooksOfAnAuthor = await (
        from j in book.Authors.JoinQueryable()
        where j.ChildID == &quot;AuthorID&quot;
        join b in DB.Collection&lt;Book&gt;() on j.ParentID equals b.ID
        select b
).ToListAsync();

//Lambda syntax
var allBooksOfAnAuthor = await book.Authors
        .JoinQueryable()
        .Where(j =&gt; j.ChildID == &quot;AuthorID&quot;)
        .Join(
            DB.Collection&lt;Book&gt;(), //foreign collection
            j =&gt; j.ParentID,       //local ID
            b =&gt; b.ID,             //foreign ID
            (j, b) =&gt; b)           //result selector expression
        .ToListAsync();
</code></pre>
<p>in cases where you don't have access to an instance of the parent entity and only have the <code>ID</code> of the parent, you can access the join records like so:</p>
<pre><code class="lang-csharp">DB.Entity&lt;Book&gt;(&quot;Book ID&quot;).Authors.JoinQueryable()
</code></pre>
<p>and when you need to access all of the join records for a given entity relationship, you can access the join records like so:</p>
<pre><code class="lang-csharp">DB.Entity&lt;Book&gt;().Authors.JoinQueryable()
</code></pre>
<h2 id="counting-children">Counting children</h2>
<p>you can get how many entities are there in the opposite side of any relationship as shown below:</p>
<pre><code class="lang-csharp">var authorCount = await book.Authors.ChildrenCountAsync();
var bookCount = await author.Books.ChildrenCountAsync();
</code></pre>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
